package com.jt.permission.helper;

import com.jt.base.utils.Constant;
import com.jt.permission.model.Menu;
import org.springframework.stereotype.Component;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author longheping
 * @date 2018/7/6 8:24
 */
@Component
public class MenuHelper {

    /**
     * 菜单折叠成树状
     */
    public List<Menu> treeMenu(List<Menu> list, boolean hasButton) {
        if (list == null) {
            return null;
        }
        //查询目录类菜单
        List<Menu> catalogMenuList = list.stream().
                filter(menu -> menu.getType() == Constant.MenuType.CATALOG.getValue())
                .sorted(Comparator.comparingInt(Menu::getOrderNum))
                .collect(Collectors.toList());
        //查询url类菜单
        List<Menu> menuList = list.stream().filter(menu -> menu.getType() == Constant.MenuType.MENU.getValue())
                .sorted(Comparator.comparingInt(Menu::getOrderNum))
                .collect(Collectors.toList());
        //查询按钮类菜单
        List<Menu> buttonMenuList = list.stream().filter(menu -> menu.getType() == Constant.MenuType.BUTTON.getValue())
                .sorted(Comparator.comparingInt(Menu::getOrderNum))
                .collect(Collectors.toList());
        if (hasButton) {
            menuList.stream().forEach(menu ->
                    {
                        List<Menu> children = buttonMenuList.stream()
                                .filter(m -> m.getParentId().equals(menu.getMenuId()))
                                .collect(Collectors.toList());
                        if (children != null && children.size() > 0) {
                            menu.setChildren(children);
                        }
                    }
            );
        }
        catalogMenuList.stream().forEach(menu -> {
                    List<Menu> children = menuList.stream()
                            .filter(m -> m.getParentId().equals(menu.getMenuId()))
                            .collect(Collectors.toList());
                    if (children != null && children.size() > 0) {
                        menu.setChildren(children);
                    }
                }
        );
        return catalogMenuList;
    }


}
